<?php
class Post_model extends CI_Model {
	
	function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
    
    public function find_by_id ($id) {
    	$this->db->where('id', intval($id));
		return $this->db->get('posts')->row_array();
    }
    
	public function add($data) {
		$this->db->insert("posts", $data);
		$post_id = $this->db->insert_id();
		if ($data['is_thread'] != 1) {
			$sql = " update threads set modified='" . $data['created'] . "',last_poster =" . $data['created_by'] . ", reply_count=reply_count+1 where id=" . intval($data['thread_id']) . " limit 1";
			$this->db->query($sql);
		}
		return $post_id;
	}
	/**
	 * 回帖数量
	 * @param int $thread_id
	 */
	public function get_count_by_thread_id ($thread_id) {
		$sql = " select count(*) as total from posts  where thread_id=" . intval($thread_id);
		$result = $this->db->query($sql)->row_array();
		return $result['total'];
	}
	/**
	 * 回帖列表
	 * @param int $thread_id
	 * @param int $offset
	 * @param int $limit
	 */
	public function find_by_thread_id ($thread_id, $offset = 0, $limit = 10) {
		$sql = " select p.*,u.nickname,u.thumb_avatar,concat(pr.province,c.city) as address from posts p 
		left join users u on p.created_by=u.id 
		left join province pr on pr.provinceID=u.province_id
		left join city c on u.city_id = c.cityID 
		where p.thread_id=" . intval($thread_id);
		
		$sql .= " order by is_thread desc , created asc ";
		$sql .= " limit " . $offset . ", " . $limit;
		return $this->db->query($sql)->result_array();
	}
	/**
	 * 删除
	 * @param int $id
	 */
	public function delete ($id) {
		$post = $this->find_by_id($id);
		if (!empty($post)) {
			$this->db->delete('posts', array('id' => $id)); 
			$sql = " update threads set reply_count = reply_count - 1 where id=" . intval($post['thread_id']) . " limit 1";
			$this->db->query($sql);
		}
		return 1;
	}
	
	/**
	 * 回帖的页码
	 * @param int $post_id
	 * @param int $thread_id
	 */
	public function get_page_num($post_id, $thread_id) {
		$sql = " select count(*) as total from posts  where thread_id=" . intval($thread_id) . " and id<" . $post_id;
		
		$result = $this->db->query($sql)->row_array();
		//print_r($result);
		return  floor($result['total']/LA_PAGE_SIZE) * LA_PAGE_SIZE;
	}
}